# 导入必要的包
import torch.utils.data
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms

# GPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 超参数
input_size = 784  # 手写数字图片为28*28*1，维度为784
hidden_size = 500  # 隐藏层
num_classes = 10  # 类别
num_epochs = 5  # 训练次数
batch_size = 100
learning_rate = 0.001  # 学习率

# 手写数字集下载
# transforms.ToTensor()先由HWC转变成CHW，除以255转为像素到[0,1]之间的浮点型
train_dataset = torchvision.datasets.MNIST(root='../data',
                                           train=True,
                                           transform=transforms.ToTensor(),
                                           download=True)
test_dataset = torchvision.datasets.MNIST(root='../data',
                                          train=False,
                                          transform=transforms.ToTensor())
# 数据集加载
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=batch_size,
                                          shuffle=False)

# 定义模型,并放到gpu上面
# 逻辑回归与前向传播不同
model = nn.Linear(input_size, num_classes).to(device)

# 定义损失函数与优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# 训练模型
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        # 图像进行维度修改28*28*1----->784,搬到gpu上面
        images = images.reshape(-1, 28 * 28).to(device)
        labels = labels.to(device)

        # 前向传播
        outputs = model(images)
        loss = criterion(outputs, labels)

        # 反向传播与参数优化
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i + 1) % 100 == 0:
            print('Epoch: {}/{},step: {}/{},loss: {:.4f}'
                  .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))

with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, 28 * 28).to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy: {} %'.format(100 * correct / total))

# 保存模型
torch.save(model.state_dict(), 'model.ckpt')
